package com.chart.web.controller.chart.sta;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.chart.chart.domian.ChartConfigs;
import com.chart.chart.domian.dto.ChartDateTto;
import com.chart.chart.domian.utils.ChartValidator;
import com.chart.chart.domian.vo.ChartSmartVo;
import com.chart.chart.service.IChartConfigsService;
import com.chart.common.core.controller.BaseController;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.utils.ChartDataUtils;
import com.chart.common.utils.ExcelDataUtils;
import com.chart.common.utils.ExcelUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 漏斗图
 *
 * @author chart
 */
@Slf4j
@RestController
@RequestMapping("/funnel/chart")
public class FunnelChartController extends BaseController
{


    @Autowired
    private IChartConfigsService chartConfigsService;



    @PostMapping("/importData1")
    public AjaxResult importData(@RequestBody ChartDateTto chartDateTto) throws Exception {
        //参数校验
        ChartValidator.check(chartDateTto);
        try {
            String chartValue = chartDateTto.getChartValue();
            List<List<String>> lists = ChartDataUtils.extractDataFromList(chartDateTto.getDataList());

            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode chartValueJson = objectMapper.readTree(chartValue);

            // 获取dataset节点
            ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");
            // 更新dataset中的source节点
            dataset = ChartDataUtils.updateDatasetSources(dataset, lists, objectMapper);

            // 移除集合中第一个对象的第一个元素
            if (!lists.isEmpty() && !lists.get(0).isEmpty()) {
                lists.get(0).remove(0);
            }

            // 获取series字段并删除其余对象
            ArrayNode seriesArray = (ArrayNode) chartValueJson.path("series");
            if (seriesArray.size() > 1) {
                while (seriesArray.size() > 1) {
                    seriesArray.remove(1);
                }
            }

            // 计算第一个对象剩余元素数量
            int firstObjectRemainingElements = lists.isEmpty() ? 0 : lists.get(0).size();
            // 复制series的第一个对象
            JsonNode firstSeriesObject = seriesArray.get(0);
            for (int i = 1; i < firstObjectRemainingElements; i++) {
                seriesArray.add(firstSeriesObject.deepCopy());
            }

            // 在这里添加新的逻辑来处理 datasetIndex 字段
            for (int i = 0; i < seriesArray.size(); i++) {
                ObjectNode seriesObject = (ObjectNode) seriesArray.get(i);
                if (seriesObject.has("datasetIndex")) {
                    seriesObject.put("datasetIndex", i);
                } else {
                    seriesObject.put("datasetIndex", i);
                }
            }

            // 获取legend节点并更新data
            JsonNode legend = chartValueJson.path("legend");
            ChartDataUtils.updateLegendData(legend, lists);

            // 更新series中每个对象的name字段
            for (int i = 0; i < firstObjectRemainingElements; i++) {
                ((ObjectNode) seriesArray.get(i)).put("name", lists.get(0).get(i));
            }
            String updatedChartValue = chartValueJson.toString();

            ArrayList<ChartSmartVo> newList = new ArrayList<>();
            // 获取ChartConfigs对象
            ChartConfigs configs = chartConfigsService.getById(chartDateTto.getConfigId());
            if (ObjectUtils.isEmpty(configs)) {
                log.error("未找到图表配置。配置ID={}", chartDateTto.getConfigId());
                return AjaxResult.error("未找到该图表的配置，请检查配置ID是否正确。");
            }
            // 创建新的ChartSmartVo对象并设置属性
            ChartSmartVo chartSmartVo = new ChartSmartVo();
            chartSmartVo.setConfigId(configs.getId()); // 假设ChartConfigs有getId方法
            chartSmartVo.setConfigName(configs.getConfigName()); // 假设ChartConfigs有getName方法
            chartSmartVo.setConfigValue(updatedChartValue);
            chartSmartVo.setChartTypeId(configs.getChartTypeId());

            newList.add(chartSmartVo);
            System.out.println(updatedChartValue);
            return AjaxResult.success(newList);
        } catch (JsonProcessingException e) {
            logger.error("/importData1,configId={}发生异常",chartDateTto.getConfigId());
            throw new RuntimeException(e);
        }
    }



/*
    @PostMapping("/importData1")
    public AjaxResult importData(MultipartFile file,Long configId) throws Exception {
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            List<JSONObject> list = new ArrayList<>();


            for (int i = 2; i < getdata.size(); i++) {
                List<String> strings = getdata.get(i);
                JSONObject jsonObject = new JSONObject();
                for (int i1 = 0; i1 < strings.size(); i1++) {
                    String s = strings.get(i1);
                    if (ObjectUtils.isNotEmpty(s) && !s.equals("")) {
                        if (i1 == 0) {
                            jsonObject.put("name", s);
                        } else if(i1 == 1) {
                            jsonObject.put("value", Double.parseDouble(s));
                        }
                    }
                }
                list.add(jsonObject);
            }


            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());


            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            for (int i = 0; i < series.size(); i++) {
                JSONObject jsonObject1 = series.get(i);
                jsonObject1.put("data", list);
            }

            jsonObject.put("series", series);

            return AjaxResult.success(JSON.toJSONString(jsonObject));
        }finally {
            workbook.close();
        }
    }*/

    @PostMapping("/v2/importData1")
    public AjaxResult v2importData(@RequestBody List<Map<String, Object>> dataLists, Long configId) throws Exception {
        XSSFWorkbook workbook = null;
        try {
          /*  workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);*/

            Sheet sheet = ExcelUtils.convertDataListToSheetRemoveNineAndOne(dataLists);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            List<JSONObject> list = new ArrayList<>();


            for (int i = 2; i < getdata.size(); i++) {
                List<String> strings = getdata.get(i);
                JSONObject jsonObject = new JSONObject();
                for (int i1 = 0; i1 < strings.size(); i1++) {
                    String s = strings.get(i1);
                    if (ObjectUtils.isNotEmpty(s) && !s.equals("")) {
                        if (i1 == 0) {
                            jsonObject.put("name", s);
                        } else if(i1 == 1) {
                            jsonObject.put("value", Double.parseDouble(s));
                        }
                    }
                }
                list.add(jsonObject);
            }


            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());


            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            for (int i = 0; i < series.size(); i++) {
                JSONObject jsonObject1 = series.get(i);
                jsonObject1.put("data", list);
            }

            jsonObject.put("series", series);

            return AjaxResult.success(JSON.toJSONString(jsonObject));
        }finally {
            workbook.close();
        }
    }
}
